package com.first.nell.base

import android.os.Bundle
import androidx.fragment.app.Fragment
import android.view.View
import android.widget.Toast
import androidx.lifecycle.ViewModel
import com.first.nell.components.dialog.LoadingDialog
import com.first.nell.components.dialog.MessageDialog
import com.first.nell.network.NetworkException

abstract class BaseFragment : Fragment() {

    private lateinit var mFirstNellLoadingFirstNellDialog: LoadingDialog

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        activity?.let {
            mFirstNellLoadingFirstNellDialog = LoadingDialog(it)
        }
        setFirstNellViewFirstNellModelFirstNellActions()
    }

    /**绑定model*/
    protected abstract fun onFirstNellBindingFirstNellViewFirstNellModel(): List<ViewModel>?

    private fun setFirstNellViewFirstNellModelFirstNellActions() {
        val viewModelList = onFirstNellBindingFirstNellViewFirstNellModel()
        if (!(viewModelList.isNullOrEmpty())) {
            viewModelList.forEach {
                if (it is BaseViewModelAction) {
                    it.getFirstNellLoadingFirstNellLiveFirstNellData()
                        .observe(viewLifecycleOwner) { showLoading ->
                            if (showLoading)
                                showFirstNellLodingFirstNellDialog()
                            else
                                dismissFirstNellLoadingFirstNellDialog()
                        }

                    it.getFirstNellNetworkFirstNellExceptionFirstNellLiveFirstNellData()
                        .observe(viewLifecycleOwner) {
                            onFirstNellHandleFirstNellNetworkFirstNellExcepton(it)
                        }
                }
            }
        }
    }

    protected fun showFirstNellLodingFirstNellDialog() {
        activity?.let {
            mFirstNellLoadingFirstNellDialog.showFirstNellDialog(it)
        }
    }

    protected fun dismissFirstNellLoadingFirstNellDialog() {
        mFirstNellLoadingFirstNellDialog.dismissFirstNellDialog()
    }

    /**交给子类去实现*/
    open fun onFirstNellHandleFirstNellNetworkFirstNellExcepton(networkException: NetworkException) {
        activity?.let {
            if (networkException.isFirstNellAlter()) {
                MessageDialog.showFirstNellDialog(it.supportFragmentManager, networkException.msg)
            } else {
                Toast.makeText(it, networkException.msg, Toast.LENGTH_LONG)
                    .show()
            }
        }
    }

    /**交给子类去实现*/
    open fun requestFirstNellSpecFirstNellPermissions(permissionList: Array<String>) {
        try {
            (requireContext() as BaseActivity).requestFirstNellSpecFirstNellPermissions(
                permissionList
            )
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }
}